<meta charset="utf-8">
(#) Handler reference leaks

!!! WARNING: Handler reference leaks
   This is a warning.

Id
:   `HandlerLeak`
Summary
:   Handler reference leaks
Severity
:   Warning
Category
:   Performance
Platform
:   Android
Vendor
:   Android Open Source Project
Feedback
:   https://issuetracker.google.com/issues/new?component=192708
Since
:   Initial
Affects
:   Kotlin and Java files
Editing
:   This check runs on the fly in the IDE editor
Implementation
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/HandlerDetector.java)
Tests
:   [Source Code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/HandlerDetectorTest.java)
Copyright Year
:   2012

Since this Handler is declared as an inner class, it may prevent the
outer class from being garbage collected. If the Handler is using a
`Looper` or `MessageQueue` for a thread other than the main thread, then
there is no issue. If the `Handler` is using the `Looper` or
`MessageQueue` of the main thread, you need to fix your `Handler`
declaration, as follows: Declare the `Handler` as a static class; In the
outer class, instantiate a `WeakReference` to the outer class and pass
this object to your `Handler` when you instantiate the `Handler`; Make
all references to members of the outer class using the `WeakReference`
object.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/test/pkg/HandlerTest.java:12:Warning: This Handler class should be
static or leaks might occur (test.pkg.HandlerTest.Inner) [HandlerLeak]
    public class Inner extends Handler { // ERROR
                 -----
src/test/pkg/HandlerTest.java:18:Warning: This Handler class should be
static or leaks might occur (anonymous android.os.Handler)
[HandlerLeak]
    Handler anonymous = new Handler() { // ERROR
                        ^
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`src/test/pkg/HandlerTest.java`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~java linenumbers
package test.pkg;
import android.os.Looper;
import android.os.Handler;
import android.os.Message;

public class HandlerTest extends Handler { // OK
    public static class StaticInner extends Handler { // OK
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
        }
    }
    public class Inner extends Handler { // ERROR
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
        }
    }
    void method() {
        Handler anonymous = new Handler() { // ERROR
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
            }
        };

        Looper looper = null;
        Handler anonymous2 = new Handler(looper) { // OK
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
            }
        };
    }

    public class WithArbitraryLooper extends Handler {
        public WithArbitraryLooper(String unused, Looper looper) { // OK
            super(looper, null);
        }

        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
        }
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/HandlerDetectorTest.java)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `HandlerDetector.testRegistered`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=192708.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("HandlerLeak")
  fun method() {
     problematicStatement()
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("HandlerLeak")
  void method() {
     problematicStatement();
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection HandlerLeak
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;lint&gt;
      &lt;issue id="HandlerLeak" severity="ignore" /&gt;
  &lt;/lint&gt;
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'HandlerLeak'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore HandlerLeak ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>